package ai.people.netmon.youtube.probe.service.impl;

import ai.people.core.standard.fill.entity.Msg;
import ai.people.core.standard.fill.service.SendNewAccountToTopicService;
import ai.people.core.standard.gather.service.AccountGatherSyncService;
import ai.people.netmon.framework.businessenum.ImportanceDegEnum;
import ai.people.netmon.framework.businessenum.NewAccountNeedFillTopicEnum;
import ai.people.netmon.framework.businessenum.gather.GatherStatusEnum;
import ai.people.netmon.framework.constant.SourceCollectionConstant;
import ai.people.netmon.framework.domain.gather.config.GatherSyncExtended;
import ai.people.netmon.framework.domain.youtube.probe.entity.YoutubeAccount;
import ai.people.netmon.framework.domain.youtube.probe.request.YoutubeAccountRequest;
import ai.people.netmon.framework.domain.youtube.probe.vo.YoutubeAccountVO;
import ai.people.netmon.framework.exception.enums.AccountExceptionEnum;
import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.framework.utils.AssertUtils;
import ai.people.netmon.youtube.probe.mapper.YoutubeAccountServiceMapper;
import ai.people.netmon.youtube.probe.service.YoutubeAccountService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.OffsetDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * youtube用户服务impl
 *
 * @author yuanqinglong
 * @date 2022/2/25 16:42
 */
@Service
@Slf4j
public class YoutubeAccountServiceImpl extends ServiceImpl<YoutubeAccountServiceMapper, YoutubeAccount> implements YoutubeAccountService, AccountGatherSyncService<YoutubeAccount>, SendNewAccountToTopicService {

    @Autowired
    private YoutubeAccountServiceMapper youtubeAccountServiceMapper;

    @Value("${data-sync-url}")
    private String dataSyncUrl;
    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    YoutubeAccountServiceMapper mapper;

    /**
     * 获取用户
     *
     * @param id id
     * @return {@link YoutubeAccountVO}
     */
    @Override
    public YoutubeAccount getAccount(Long id) {
        YoutubeAccount account = this.getById(id);
        AssertUtils.isNotNull(account, AccountExceptionEnum.ACCOUNT_DOES_NOT_EXIST);
        return account;
    }

    /**
     * 保存youtube用户
     *
     * @param youtubeAccount youtube帐户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveYoutubeAccount(YoutubeAccount youtubeAccount) {
        if (StringUtils.isBlank(youtubeAccount.getCollectionFrequency())) {
            youtubeAccount.setCollectionFrequency(SourceCollectionConstant.COLLECTION_FREQUENCY_STR);
        }
        youtubeAccount.setCollectionStatus(GatherStatusEnum.TO_BE_COLLECTED.getCode());
        int insertResult = youtubeAccountServiceMapper.insert(youtubeAccount);
        AssertUtils.isTrue(insertResult > 0, CommonEnum.FAIL);
        sendNewAccountData(NewAccountNeedFillTopicEnum.NEW_ACCOUNT_NEED_FILL_YOUTUBE.name(), new Msg(youtubeAccount), kafkaTemplate);
    }


    /**
     * 批量保存youtube用户
     *
     * @param list youtube帐户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveYoutubeAccount(List<YoutubeAccount> list) {
        AssertUtils.isTrue(!CollectionUtils.isEmpty(list), CommonEnum.FAIL);
        log.info("接收数据条数:{}",list.size());
        list = list.stream().filter(x -> Objects.nonNull(x) && StringUtils.isNotBlank(x.getAccountName())).peek(x -> {
            x.setCollectionStatus(GatherStatusEnum.TO_BE_COLLECTED.getCode());
            if (StringUtils.isBlank(x.getCollectionFrequency())) {
                x.setCollectionFrequency(SourceCollectionConstant.COLLECTION_FREQUENCY_STR);
            }
        }).collect(Collectors.toList());
        log.info("过滤为空数据条数:{}",list.size());
        List<String> accountNames = list.stream().map(YoutubeAccount::getAccountName).collect(Collectors.toList());
        LambdaQueryWrapper<YoutubeAccount> queryWrapper = Wrappers.lambdaQuery();
        //去数据库查询一遍哪些重复
        List<YoutubeAccount> already = list(queryWrapper.select(YoutubeAccount::getAccountName).in(YoutubeAccount::getAccountName, accountNames));
        if (!CollectionUtils.isEmpty(already)) {
            //删除重复的
            Set<String> alreadyName = already.stream().map(YoutubeAccount::getAccountName).collect(Collectors.toSet());
            list = list.stream().filter(x -> !alreadyName.contains(x.getAccountName())).distinct().collect(Collectors.toList());
        }
        log.info("过滤重复后剩余数据条数:{}",list.size());
        if (!CollectionUtils.isEmpty(list)) {
            boolean b = saveBatch(list);
            AssertUtils.isTrue(b, CommonEnum.FAIL);
            log.info("批量保存数量:{}", list.size());
            //推送kafka
            List<Msg> msgList = new ArrayList<>();
            list.forEach(x -> msgList.add(new Msg(x)));
            this.sendNewAccountData(NewAccountNeedFillTopicEnum.NEW_ACCOUNT_NEED_FILL_YOUTUBE.name(), msgList, kafkaTemplate);
        }
    }

    /**
     * youtube用户更新
     *
     * @param youtubeAccount youtube帐户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateYoutubeAccount(YoutubeAccount youtubeAccount) {
        Long id = youtubeAccount.getId();
        AssertUtils.isTrue(id != null, CommonEnum.CHECK_NOT_EMPTY_PRIMARY_ID);

        String newImportanceDeg = youtubeAccount.getImportanceDeg();
        int ordinaryCode = ImportanceDegEnum.ORDINARY.getCode();
        if (StringUtils.isNotBlank(newImportanceDeg) && Integer.parseInt(newImportanceDeg) >= ordinaryCode) {
            YoutubeAccount old = getById(id);
            update(youtubeAccount);
            int oldImportanceDeg = Optional.ofNullable(old.getImportanceDeg()).map(Integer::valueOf).orElse(ordinaryCode);
            if (Integer.parseInt(newImportanceDeg) >= oldImportanceDeg) {
                this.syncGatherAccount(Collections.singletonList(getById(id)), dataSyncUrl, new GatherSyncExtended());
            }
        }else {
            update(youtubeAccount);
        }
    }

    private void update(YoutubeAccount youtubeAccount) {
        youtubeAccount.setUpdateTime(OffsetDateTime.now());
        boolean b = updateById(youtubeAccount);
        AssertUtils.isTrue(b, CommonEnum.FAIL);
    }

    /**
     * youtube帐户列表视图
     *
     * @param youtubeAccountRequest youtube帐户请求
     * @return {@link PageResponse}<{@link YoutubeAccount}>
     */
    @Override
    public PageResponse<YoutubeAccount> listYoutubeAccount(YoutubeAccountRequest youtubeAccountRequest) {
        Page<YoutubeAccount> youtubePage = new Page<>(youtubeAccountRequest.getOriginPageNo(), youtubeAccountRequest.getPageSize());
        IPage<YoutubeAccount> selectPage = mapper.listYoutubeAccountPage(youtubePage, youtubeAccountRequest);
        return PageResponse.builder(selectPage);
    }


    /**
     * 更新采集状态
     *
     * @param account 账户
     */
    @Override
    public void updateCollectionStatus(List<YoutubeAccount> account) {
        account.forEach(x -> {
            x.setCollectionStatus(GatherStatusEnum.COLLECTED.getCode());
            x.setUpdateTime(OffsetDateTime.now());
        });
        this.updateBatchById(account);
    }
}
